package com.lagou.task04;

import java.io.*;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class ClientTest {

    public static void main(String[] args) {

        UserMessage tum1 = new UserMessage("check",new User("张三","123456"));
        UserMessage tum2 = new UserMessage("check",new User("李四","123456"));
        UserMessage tum3 = new UserMessage("check",new User("admin","123456"));

        LinkedList list = new LinkedList();
        list.add(tum1);
        list.add(tum2);
        list.add(tum3);

        Socket s = null;
        Scanner sc = new Scanner(System.in);
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;

        try {
            // 1.创建 Socket 类型的对象，用于连接服务器
            s = new Socket("127.0.0.1",8888);
            System.out.println("连接服务端成功");

            // 创建输出流 用于发送消息
            oos = new ObjectOutputStream(s.getOutputStream());
            // 创建输入流 用于接收消息
            ois = new ObjectInputStream(s.getInputStream());

            // 2.输入输出流通信
            while (true){
                System.out.println();
                System.out.println("请输入要发送的对象编号：1,2,或3。按下 0 表示断开连接");
                int inputNo = sc.nextInt();
                if (inputNo > 0 && inputNo < 4) {
                    // 发送 UserMessage 对象给服务端
                    oos.writeObject(list.get(inputNo - 1));
                    System.out.println("发送成功");
                }else {
                    //传出 null 表示聊天结束
                    oos.writeObject(null);
                    break;
                }

                //接收服务端发来的消息
                UserMessage userMessage = (UserMessage)ois.readObject();
                System.out.println("客户端收到对象消息：" + userMessage);
                if (userMessage.getType().equals("success")){
                    System.out.println("登录成功");
                    //传出 null 表示聊天结束
                    oos.writeObject(null);
                    break;
                }else{
                    System.out.println("登录失败");
                }
                System.out.println();
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 3.关闭
            if (null != ois){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            sc.close();
            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
